﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Transactions;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using DotNetOpenAuth.AspNet;
using Microsoft.Web.WebPages.OAuth;
using WebMatrix.WebData;
using FCDB.Web.Filters; 
using FB.Services;
using FB.Membership.Annotations;
using FB.Membership.Principal;
using System.Web.Script.Serialization;
using FCDB.Web.Models;
using FB.Enums;
 

namespace FCDB.Web.Controllers
{
    
    public class AccountController : FB.Mvc.Controllers.AccountBaseController<FB.Services.AccountServiceBase>
    {
         private LoggingService _LogService = new LoggingService();
         //
         // GET: /Account/
         public AccountController() : base(new FB.Services.AccountServiceBase()) { }
         public ActionResult Login()
         {

             LogOnViewModel model = new LogOnViewModel();
             return View(model);
         }
         [HttpPost]
         public ActionResult Login(LogOnViewModel model, string returnUrl)
         {
             string code = Session["GoogleCode"] as string;
             if (!string.IsNullOrEmpty(code) && code.ToLower() != Request["Captcha"].ToLower())
             {
                 ModelState.AddModelError("", "验证码错误！");
                 model.ErrorStr = "验证码错误";
                 return View(model);
             }
             if (ModelState.IsValid)
             {

                 //MembershipUser user = Membership.GetUser(model.UserName);
                 //user.ChangePassword(user.ResetPassword(), "abc@123"); 
                 if (Membership.ValidateUser(model.UserName, model.Password))
                 {
                     // check service access rights
                     if (HasThisService(model.UserName))
                     {
                         _service.SetAuthenCookie(model.UserName, model.RememberMe);
                         if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/")
                             && !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
                             return Redirect(returnUrl);
                         //else
                         //    if (model.Password != "abc@123" && model.Password != "abc123")
                         //        return RedirectToAction("Index", "Default");
                         //    else
                         //    {
                         //        ModelState.AddModelError("", "初始密码，需要修改！");
                         //        model.ErrorStr = "初始密码，需要修改";
                         //        return View(model);
                         //    }
                         return RedirectToAction("Index", "Default");
                     }
                     else
                     {
                         ModelState.AddModelError("", "You are not allowed to use this application.");
                         model.ErrorStr = "You are not allowed to use this application.";
                         _service_log.LogAccess(model.UserName, AccessStatus.Application_Denied);
                     }
                 }
                 else
                 {
                     ModelState.AddModelError("", "你的账号名称或密码错误");
                     model.ErrorStr = "你的账号名称或密码错误";
                     _service_log.LogAccess(model.UserName, AccessStatus.Sign_In_Fail);
                 }
             }
             return View(model);
         }

         //
         // GET: /Account/LogOff
         [AuthorizeOnly]
         public ActionResult LogOff()
         {
             _service.SignOutAndCleanSession(FBIdentity);
             return RedirectToAction("Login", "Account");
         }

         public ActionResult Register()
         {
             return View();
         }
         [HttpPost]
         public ActionResult Register(RegisterViewModel model)
         {
             if (ModelState.IsValid)
             {

                 MembershipCreateStatus createStatus;
                 Membership.CreateUser(model.UserName, model.Password, model.Email, null, null, true, null, out createStatus);

                 if (createStatus == MembershipCreateStatus.Success)
                 {
                     var identity = new FBIdentityCookieModel { Name = model.UserName, UserId = (Guid)Membership.GetUser(model.UserName).ProviderUserKey };
                     var serializer = new JavaScriptSerializer();
                     string userData = serializer.Serialize(identity);

                     FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(1,
                                  identity.Name, DateTime.Now, DateTime.Now.AddMinutes(15), false, userData);

                     string encTicket = FormsAuthentication.Encrypt(authTicket);
                     HttpCookie faCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encTicket);
                     Response.Cookies.Add(faCookie);



                     return RedirectToAction("Index", "Default");
                 }
                 else
                 {
                     ModelState.AddModelError("", ErrorCodeToString(createStatus));
                 }
             }

             // If we got this far, something failed, redisplay form
             return View(model);
         }

         //
         // GET: /Account/ChangePassword

         [AuthorizeOnly]
         public ActionResult ChangePassword()
         {
             ViewBag.UserName = this.UserName;
             return View();
         }
         [AuthorizeOnly]
         [HttpPost]
         public string ChangePassword(ChangePasswordViewModel model)
         {
             // ChangePassword will throw an exception rather
             // than return false in certain failure scenarios.
             bool changePasswordSucceeded;
             string return_str;
             try
             {
                 MembershipUser currentUser = Membership.GetUser(User.Identity.Name, true /* userIsOnline */);
                 changePasswordSucceeded = currentUser.ChangePassword(model.OldPassword, model.NewPassword);
             }
             catch (Exception)
             {
                 changePasswordSucceeded = false;
             }

             if (changePasswordSucceeded)
             {
                 return_str = "密码修改成功";
             }
             else
             {
                 return_str = "你的账号名称或密码错误";
                 ModelState.AddModelError("", "你的账号名称或密码错误");
             }


             // If we got this far, something failed, redisplay form
             return return_str;
         }





         #region Status Codes
         private static new string ErrorCodeToString(MembershipCreateStatus createStatus)
         {
             // See http://go.microsoft.com/fwlink/?LinkID=177550 for
             // a full list of status codes.
             switch (createStatus)
             {
                 case MembershipCreateStatus.DuplicateUserName:
                     return "User name already exists. Please enter a different user name.";

                 case MembershipCreateStatus.DuplicateEmail:
                     return "A user name for that e-mail address already exists. Please enter a different e-mail address.";

                 case MembershipCreateStatus.InvalidPassword:
                     return "The password provided is invalid. Please enter a valid password value.";

                 case MembershipCreateStatus.InvalidEmail:
                     return "The e-mail address provided is invalid. Please check the value and try again.";

                 case MembershipCreateStatus.InvalidAnswer:
                     return "The password retrieval answer provided is invalid. Please check the value and try again.";

                 case MembershipCreateStatus.InvalidQuestion:
                     return "The password retrieval question provided is invalid. Please check the value and try again.";

                 case MembershipCreateStatus.InvalidUserName:
                     return "The user name provided is invalid. Please check the value and try again.";

                 case MembershipCreateStatus.ProviderError:
                     return "The authentication provider returned an error. Please verify your entry and try again. If the problem persists, please contact your system administrator.";

                 case MembershipCreateStatus.UserRejected:
                     return "The user creation request has been canceled. Please verify your entry and try again. If the problem persists, please contact your system administrator.";

                 default:
                     return "An unknown error occurred. Please verify your entry and try again. If the problem persists, please contact your system administrator.";
             }
         }
         #endregion
    }
}
